﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using VisionCloud.Api.Auth;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Applet.RequestDto;
using VisionCloud.Domain.DtoModel.Sys;
using VisionCloud.Domain.Filters;

namespace VisionCloud.Api.Controllers.Applet
{
    /// <summary>
    /// 权限验证
    /// </summary>
    [SystemModule("小程序模块")]
    [ApiAuthorize(PolicyEnum.RequireRolePermission)]
    [ApiVersion("1.0")]
    [Route("api/applet/[controller]/[Action]")]
    [ApiExplorerSettings(GroupName = "小程序模块")]
    public class AuthController : AuthBaseControlller
    {
        /// <summary>
        /// 用户退出登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ApiExplorerSettings(IgnoreApi = true)]
        public async Task<ApiResult> Logout()
        {
            return await TryCatchAsync(UserService.Logout(TokenModel, AuthCore.GetExpires(), () =>
            {
                Cached.Remove($"Applet:{TokenModel.Id}:OpenId");
            }));
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="modelDto"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<ApiResult> Login(LogInDto modelDto)
        {
            SysUserDto sysUserDto = new SysUserDto();
            sysUserDto.Email = modelDto.Email;
            sysUserDto.Password = modelDto.Password;
            sysUserDto.TokenType = TokenTypeEnum.Applet;
            return await TryCatchAsync(GetToken(sysUserDto, modelDto.JsCode));
        }

        /// <summary>
        /// 游客用户登录
        /// </summary>
        [AllowAnonymous]
        [HttpPost]
        public async Task<ApiResult> VistorLogin(VistorLoginDto modelDto) => await TryCatchAsync(GetTokenForVistor(TokenTypeEnum.Applet, modelDto.JsCode));
    }
}